<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课题分类" prop="cateId">
        <treeselect v-model="queryParams.cateId" :options="categoryOptions" :normalizer="normalizer" placeholder="请选择课题分类" style="width:240px"/>
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择级别" clearable size="small">
          <el-option
            v-for="dict in levelOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="masterUserId">
        <el-select v-model="queryParams.masterUserId" clearable filterable placeholder="请输入姓名选择">
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.nickName + '('+item.userName+')'"
            :value="item.userId"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目周期" prop="finishTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="当前进度" prop="progress">
        <el-select v-model="queryParams.progress" placeholder="请选择当前进度" clearable size="small">
          <el-option
            v-for="dict in judgeTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否结题" prop="completeStatus">
        <el-select v-model="queryParams.completeStatus" placeholder="请选择是否结题" clearable size="small">
          <el-option
            v-for="dict in yesnoOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['subject:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['subject:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['subject:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList">
      <el-table-column label="课题分类" align="center" prop="cateName" />
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="级别" align="center" prop="level" :formatter="levelFormat" />
      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="项目负责人" align="center" prop="masterUser.nickName" />
      <el-table-column label="项目周期" align="center" prop="startTime" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.startTime != null">{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span> 至
          <span v-if="scope.row.finishTime != null">{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经费预算" align="center" prop="budget" />
      <el-table-column label="当前进度" align="center" prop="progress" :formatter="progressFormat" />
      <el-table-column label="是否结题" align="center" prop="completeStatus" :formatter="completeStatusFormat" />
     <el-table-column label="申报文件" align="center" prop="applyFileId">
       <template slot-scope="scope">
         <el-link v-if="scope.row.applyFile != null" target="_blank"
         :href="downloadUrl(scope.row.applyFile)">下载</el-link>
       </template>
     </el-table-column>
     <el-table-column label="开题文件" align="center" prop="beginFileId">
       <template slot-scope="scope">
         <el-link v-if="scope.row.beginFile != null" target="_blank"
         :href="downloadUrl(scope.row.beginFile)">下载</el-link>
       </template>
     </el-table-column>
     <el-table-column label="中期评审文件" align="center" prop="judgeFileId">
       <template slot-scope="scope">
         <el-link v-if="scope.row.judgeFile != null" target="_blank"
         :href="downloadUrl(scope.row.judgeFile)">下载</el-link>
       </template>
     </el-table-column>
     <el-table-column label="结题文件" align="center" prop="completeFileId">
       <template slot-scope="scope">
         <el-link v-if="scope.row.completeFile != null" target="_blank"
         :href="downloadUrl(scope.row.completeFile)">下载</el-link>
       </template>
     </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.completeStatus != '1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['subject:task:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.progress == '1' && scope.row.checkStatus != '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['subject:task:remove']"
          >删除</el-button>
          <el-button v-if="scope.row.completeStatus != '1'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleCheck(scope.row)"
            v-hasPermi="['subject:task:edit']"
          >发起评审</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课题项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
       <el-tabs type="card" >
        <el-tab-pane label="基本信息">
        <el-form-item label="课题分类" prop="cateId">
          <treeselect v-model="form.cateId" :options="categoryOptions" :normalizer="normalizer" placeholder="请选择课题分类" />
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别">
            <el-option
              v-for="dict in levelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课题说明" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="预期成果" prop="results">
          <el-input v-model="form.results" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="负责人" prop="masterUserId">
          <el-select v-model="form.masterUserId" clearable filterable placeholder="请输入姓名选择">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName + '('+item.userName+')'"
              :value="item.userId"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="详细信息">
        <el-form-item label="参与人员" prop="userId">
          <el-select v-model="form.userId" clearable filterable multiple placeholder="请输入姓名选择">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName + '('+item.userName+')'"
              :value="item.userId"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="finishTime">
          <el-date-picker clearable size="small"
            v-model="form.finishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="经费预算" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入经费预算" />
        </el-form-item>
        <el-form-item label="经费来源" prop="budgetSource">
          <el-input v-model="form.budgetSource" placeholder="请输入经费来源" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注说明" />
        </el-form-item>
        <el-form-item label="申报文件">
          <fileUpload v-model="form.applyFileId"/>
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="项目进展">
        <el-form-item label="当前进度">
          <el-radio-group v-model="form.progress">
            <el-radio
              v-for="dict in judgeTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="完成情况">
          <el-radio-group v-model="form.progressStatus">
            <el-radio
              v-for="dict in checkStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否结题">
          <el-radio-group v-model="form.completeStatus">
            <el-radio
              v-for="dict in yesnoOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开题文件">
          <fileUpload v-model="form.beginFileId"/>
        </el-form-item>
        <el-form-item label="中期评审文件">
          <fileUpload v-model="form.judgeFileId"/>
        </el-form-item>
        <el-form-item label="结题文件">
          <fileUpload v-model="form.completeFileId"/>
        </el-form-item>
        </el-tab-pane>
      </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改课题评审对话框 -->
    <el-dialog title="发起评审" :visible.sync="judgeOpen" width="500px" append-to-body>
      <el-form ref="judgeForm" :model="judgeForm" :rules="rules" label-width="80px">
        <el-form-item label="评审类型" prop="type">
          <el-select v-model="judgeForm.type" placeholder="请选择评审类型">
            <el-option
              v-for="dict in judgeTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="userIds">
          <el-select v-model="judgeForm.userIds" clearable filterable multiple placeholder="请输入姓名选择">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName + '('+item.userName+')'"
              :value="item.userId"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitJudgeForm">确 定</el-button>
        <el-button @click="cancelJudge">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, exportTask } from "@/api/subject/task";
import { addJudge } from "@/api/subject/judge";
import { selectCategory } from "@/api/subject/category";
import { selectUser } from "@/api/system/user";
import FileUpload from '@/components/FileUpload';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Task",
  components: {
    FileUpload,Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课题项目表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 级别字典
      levelOptions: [],
      // 类型字典
      typeOptions: [],
      // 审核结果字典
      checkStatusOptions: [],
      // 是否结题字典
      yesnoOptions: [],
      // 课题分类树选项
      categoryOptions: [],
      judgeTypeOptions: [],
      // 用户选项
      userOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cateId: null,
        name: null,
        level: null,
        type: null,
        masterUserId: null,
        startTime: null,
        finishTime: null,
        checkStatus: null,
        completeStatus: null,
        orderByColumn:"t.id",
        isAsc:"DESC"
      },
      // 表单参数
      form: {},
      // 是否显示弹出层
      judgeOpen: false,
      // 表单参数
      judgeForm: {},
      // 表单校验
      rules: {
        cateId: [
          { required: true, message: "课题分类不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "级别不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        comment: [
          { required: true, message: "课题说明不能为空", trigger: "blur" }
        ],
        results: [
          { required: true, message: "预期成果不能为空", trigger: "blur" }
        ],
        masterUserId: [
          { required: true, message: "项目负责人不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        finishTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        budget: [
          { required: true, message: "经费预算不能为空", trigger: "blur" }
        ],
        budgetSource: [
          { required: true, message: "经费来源不能为空", trigger: "blur" }
        ],
        applyFileId: [
          { required: true, message: "申报文件不能为空", trigger: "blur" }
        ],
        beginFileId: [
          { required: true, message: "开题文件不能为空", trigger: "blur" }
        ],
        judgeFileId: [
          { required: true, message: "中期评审文件不能为空", trigger: "blur" }
        ],
        completeFileId: [
          { required: true, message: "结题文件不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("base_level").then(response => {
      this.levelOptions = response.data;
    });
    this.getDicts("subject_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("judge_type").then(response => {
      this.judgeTypeOptions = response.data;
    });
    this.getDicts("check_status").then(response => {
      this.checkStatusOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.yesnoOptions = response.data;
    });
    this.getTreeselect();
    selectUser().then(response => {
      this.userOptions = response.rows;
    });
  },
  methods: {
    /** 查询课题项目列表 */
    getList() {
      this.loading = true;
      listTask(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换课题分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.title,
        children: node.children
      };
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      selectCategory().then(response => {
        this.categoryOptions = [];
        const data = { id: 0, title: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "pid");
        this.categoryOptions.push(data);
      });
    },
    // 级别字典翻译
    levelFormat(row, column) {
      return this.selectDictLabel(this.levelOptions, row.level);
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 进度字典翻译
    progressFormat(row, column) {
      return this.selectDictLabel(this.judgeTypeOptions, row.progress) + '('
      + this.selectDictLabel(this.checkStatusOptions, row.progressStatus) + ')';
    },
    // 是否结题字典翻译
    completeStatusFormat(row, column) {
      return this.selectDictLabel(this.yesnoOptions, row.completeStatus);
    },
    /** 下载 */
    downloadUrl (file) {
      return process.env.VUE_APP_BASE_API+"/sys/files/download/"+file.id;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cateId: null,
        name: null,
        level: null,
        type: null,
        comment: null,
        results: null,
        masterUserId: null,
        userIds: null,
        userId: [],
        startTime: null,
        finishTime: null,
        budget: null,
        budgetSource: null,
        remark: null,
        checkStatus: "0",
        completeStatus: "0",
        applyFileId: null,
        beginFileId: null,
        judgeFileId: null,
        completeFileId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课题项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课题项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除课题项目编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTask(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有课题项目数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTask(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 发起评审 **/
    handleCheck(row) {
      this.judgeOpen = true;
      this.judgeForm = {
        taskId: row.id,
        type: row.checkStatus != '1' ? '1' : null,
        userIds: []
      }
    },
    // 取消按钮
    cancelJudge() {
      this.judgeOpen = false;
      this.judgeForm = {
        taskId: null,
        type: null,
        userIds: []
      }
    },
     /** 提交按钮 */
    submitJudgeForm() {
      addJudge(this.judgeForm).then(response => {
        this.msgSuccess("新增成功");
        this.judgeOpen = false;
        this.judgeForm = {
          taskId: null,
          type: null,
          userIds: []
        }
      });
    },
  }
};
</script>
